<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.yuxin.common.util.*" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.util.*" %>
<%@ page import="com.google.gson.Gson" %>
<%@ page import="com.yuxin.core.TransactionManager" %>
<%@ page import="com.yuxin.core.exception.BusinessException" %>

<%
    String action = request.getParameter("action");
    Map result = new HashMap();
    response.setContentType("text/html;charset=UTF-8");
    Map user = ((Map)session.getAttribute("user"));
    Connection conn = DBUtil.getConnection();
    TransactionManager transaction = new TransactionManager(conn);
    try{
        if("saveProduct".equals(action)){
            transaction.begin();
            
            // 判断商家是否设置了店铺
    		String trade_id  = (String)user.get("SRC_ID");
    		String sql = "select count(t.ID) from p_shop t where t.TRADE_ID = ?";	
    		int record = DBUtil.count(conn, sql, trade_id);
    		
    		if(record > 0) {
			    Map<String,String> uploadSet = new HashMap<String,String>();
			    uploadSet.put("type",FileUploadUtil.COMPRESS_SMALL_IMAGE);
			    uploadSet.put("width","100");
			    uploadSet.put("height","100");
	            Map uploadResult = FileUploadUtil.upload(request,uploadSet);
	            List<Map> fileList = (List<Map>)uploadResult.get("files");
	            Map formData = (Map)uploadResult.get("formData");
	           	//=============图册处理=================================================
	   	       	//图册
	   	    	List pictures = new ArrayList();
	           	if(!CollectionUtils.isEmpty(fileList)){
	   	    		long picid = new Date().getTime();
		   	        for(Map file : fileList){
		   	        	String filed = (String)file.get("filed");
		   	        	//处理图册
		   	        	if(filed.startsWith("IMG-")){
		   	        		formData.remove(filed);
		   	        		picid ++;//ID增长
		   	        		//单张图片信息
		   	        		Map picture = new HashMap();
		   	        		picture.put("id", picid + "");
		   	        		picture.put("name", "");
		   	        		picture.put("src", file.get("path"));
		   	        		picture.put("size", file.get("size"));
		   	        		pictures.add(picture);
		   	        	}else{
		   	            	formData.put(filed,file.get("path"));
		   	        	}
		   	        }
	           	}
	           	String[] idArray = null;
	           	if(StringUtils.hasText(formData.get("img-DELETE")) ){
		           	String deleteId = (String)formData.get("img-DELETE");
		           	if(StringUtils.hasText(deleteId)){
		           		idArray = StringUtils.tokenizeToStringArray(deleteId, ",");
		           	}
	           	}
	       		//新增操作不需要将旧值找出来
	           	if(StringUtils.hasText(formData.get("ID"))){
		        	//修改操作时需要将旧值找出来，以便删除、新增
		        	Map<String,Object> picturesval = DBUtil.queryUniqueResult(conn, "SELECT IMG FROM P_GOODS WHERE ID = ?", formData.get("ID"));
		        	String pictStr = (String)picturesval.get("IMG");
		        	//数据库中存在
		        	if(StringUtils.hasText(pictStr)){
		        		//数据库的图册List
		        		List<Map<String,Object>> picturls = JsonUtil.convertList(pictStr);
		        		//减少运算量
		        		//数据库中已存在图册数据
		        		if(picturls.size() > 0){
		        			//存在删除的数据
		        			if(idArray!= null && idArray.length>0){
			        			for(String id : idArray){
			        				for(int i = 0;i<picturls.size();i++){
			        					Map<String,Object>picture = picturls.get(i);
			        					if(id.equals(picture.get("id"))){
			        						picturls.remove(i);
			        						i--;
			        					}
			        				}
			        			}
		        			}
		        			if(picturls.size() > 0){
		        				//将现有数据与新增数据聚集到一起
		        				picturls.addAll(pictures);
		        				pictures = picturls;
		        			}
		        		}
		        	}
	           	}
	           	//存在图册图片
	           	if(pictures.size() > 0){
	           		Map pic = (Map)pictures.get(0);
	            	formData.put("TITLE_IMG",pic.get("src"));
	       	        formData.put("IMG", JsonUtil.convertString(pictures)) ;
	           	}else{
	            	formData.put("TITLE_IMG","");
	            	formData.put("IMG","");
	           	}
	           	
	            //删除表单数据中在数据库表中不存在的字段（相册file使用了多个控件名称）
	            //找出key
	            Iterator formKeyIterator = formData.keySet().iterator();
	            List<String> reKeys = new ArrayList<String>();
	            while(formKeyIterator.hasNext()){
	            	String key = (String)formKeyIterator.next();
	            	if(key.startsWith("IMG-")){
	            		reKeys.add(key);
	            	}
	            }
	            //移除key
	            for(String key: reKeys){
	            	formData.remove(key);
	            }
	           	formData.remove("img-DELETE");
	            //=======================图册处理结束==============================================
	            if(StringUtils.hasText(formData.get("ID") + "")){
	                DBUtil.update(conn,formData,"P_GOODS");
	            }else{
	                formData.put("STATUS","1");
	                formData.put("STORE_PAGE","0");
	                formData.put("INDEX_PAGE","0");
	                formData.put("ID",UUIDUtil.getUUID());
	                DBUtil.save(conn,formData,"P_GOODS");
	            }
    		} else {
            	result.put("isSuccess",false);
            	result.put("error", "您还没设置店铺，不能发布商品!");    
            	return;
    		}
	        }else if("saleOnOff".equals(action)){
		        transaction.begin();
		        Map formData = new HashMap();
		        formData.put("ID",request.getParameter("ID"));
		        formData.put("STATUS",request.getParameter("STATUS"));
		        DBUtil.update(conn,formData,"P_GOODS");
		    }else if("getGoods".equals(action)){
	            String id = request.getParameter("ID");
		    	Map dataMap = DBUtil.queryUniqueResult(conn,"SELECT * FROM P_GOODS WHERE ID = ? ",id);
	            if(!CollectionUtils.isEmpty(dataMap)){
	               result.put("data",dataMap);
	            }else{
	            	result.put("data","");
	            }
	        }
	        result.put("isSuccess",true); 
    }catch (Exception e){
        transaction.rollback();
        e.printStackTrace();
        result.put("isSuccess",false);
        result.put("error",e.getMessage());
    }finally {
        transaction.commit();
        DBUtil.close(conn);
        response.getWriter().write(JsonUtil.convertString(result));
        out.clear();
        out = pageContext.pushBody();
    }
%>